package com.gjp.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取项目根路径地址，拱前台使用 如 http://localhost:8080
 * Created by 郭金鹏 on 2018/4/1.
 */
public class BasePathInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求类型，如http
        String scheme = request.getScheme();
        //获取服务ip地址 如localhost
        String serverName = request.getServerName();
        //获取服务端口地址 如8080
        int port = request.getServerPort();
        //获取上下文路径
        String path = request.getContextPath();
        //拼接项目url地址 如http://localhost:8080
        String basePath = scheme + "://" + serverName + ":" + port + path;
        //将路径设置到session中，并取名为basePath
        request.setAttribute("basePath", basePath);
        return true;
    }
}
